//获取权限方法
var userInfo = getAuthority();
var powerlist = JSON.parse(userInfo).permissions;
/*自定义函数判断权限*/
template.defaults.imports.hasPower = function(data){
    if(powerlist.includes(data)){
        return true;
    }
    return false;
};


layui.use(['layer', 'form', 'table', 'util', 'dtree','admin','laypage'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var util = layui.util;
    var dtree = layui.dtree;
    var admin = layui.admin;
    var laypage = layui.laypage;

    var Authorization;//请求接口用
    var count = 0;//总个数
    var current=1;//当前页
    var groupName = '';//枚举分组名称
    var gid = '';//枚举id
    var vid = '';//版本值id
    var versionArr = [];//版本值数组
    var isClickRowTool = false;//是否是点击表格行工具条
    var IdentValueTree = [];//存放分组值树数据
    var IdentValueSelected = {};//分组值树选中节点

    var setting={//树设置
        identValueSetting:{//分组值树设置
            edit: {
                enable: true,
                showRemoveBtn: false,
                showRenameBtn: false,
                drag: {
                    isCopy: true,
                    isMove: false,
                    prev: false,
                    next: false,
                    inner: false
                }
            },
            data: {
                key: {
                    children: "sub",
                    isParent: "isParent",
                    title: "name"
                },
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onExpand: onExpandIdentValueTree,
                onClick: identValueOnClick
            },
            view: {
                showIcon: true,
                showLine: true
            }
        },
    }
    if(userInfo){
        var access_token = localStorage.getExpire("access_token");
        var token_type = localStorage.getExpire("token_type");
        Authorization = token_type+" "+access_token;

        getIdentGroupPower();
        getIdentGroupTablePower();
        getIdentValuePower();
        getIdentGroupTableData();
    }

    // 搜索按钮点击事件
    form.on('submit(formSubSearchTbLtrt)', function (data) {
        groupName = data.field.name;
        getIdentGroupTableData();
    });

    // 打开新增分组弹窗
    $('#add-btn-ident-group').click(function () {
        showAddGroupModel();
    });
    // 表格工具条点击事件
    table.on('tool(identGroupTable)', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;
        if (layEvent === 'edit') { // 修改
            isClickRowTool = true;
            showGroupEditModel(data);
        } else if (layEvent === 'delete') { // 删除
            isClickRowTool = true;
            showGroupDeleteModel(data);
        }else if(layEvent === 'version'){//版本管理
            isClickRowTool = true;
            showVersionModel(data);
        }
    });
    //监听表格行单击事件
    table.on('row(identGroupTable)', function(obj){
        if(!isClickRowTool){
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            IdentValueSelected = {};
            gid = obj.data.id;
            getVersionList(function (versionList) {
                versionArr = versionList;
                if(versionList.length>0){
                    var obj = {
                        versionList:versionList
                    }
                    var str = template("version-tmpl",obj);
                    document.getElementById("version-tmpl-box").innerHTML = str;
                    form.render('select');
                    vid = versionList[0].id;
                    getIdentRootValue();
                }else{
                    $("#treeTbTree").empty();
                    $("#version-tmpl-box").empty();
                    form.render('select');
                }
            });
        }
    });
    form.on('select(versionSelect)', function(data){
        vid = data.value;
        getIdentRootValue();
    });

    $("#addIdentValueBtn").click(function () {
        if(IdentValueSelected.hasOwnProperty("id")){
            openAddIdentValueModel(IdentValueSelected);
        }else{
            layer.msg("请先选中分组值节点", {icon: 2});
        }
    })
    $("#editIdentValueBtn").click(function () {
        if(IdentValueSelected.hasOwnProperty("id")&&IdentValueSelected.id!="root"){
            openEditIdentValueModel(IdentValueSelected);
        }else if(IdentValueSelected.hasOwnProperty("id")&&IdentValueSelected.id == "root"){
            layer.msg("根目录不能编辑", {icon: 2});
        }else{
            layer.msg("请先选中分组值子节点", {icon: 2});
        }
    })
    $("#deleteIdentValueBtn").click(function () {
        if(IdentValueSelected.hasOwnProperty("id")&&IdentValueSelected.id!="root"){
            openDeleteIdentValueModel(IdentValueSelected);
        }else if(IdentValueSelected.hasOwnProperty("id")&&IdentValueSelected.id == "root"){
            layer.msg("根目录不能删除", {icon: 2});
        }else{
            layer.msg("请先选中分组值子节点", {icon: 2});
        }

    })
    $("#importIdentValueBtn").click(function () {
        openImportIdentValueModel();
    })

    /*渲染分组权限*/
    function getIdentGroupPower() {
        var str = template("ident-group-tmpl",{});
        document.getElementById("ident-group-tmpl-box").innerHTML = str;
    }
    /*渲染分组表格里的权限*/
    function getIdentGroupTablePower() {
        var str = template("ident-group-tableHandle-tmp",{});
        document.getElementById("ident-group-tableHandle-box").innerHTML = str;
    }
    /*渲染分组值权限*/
    function getIdentValuePower() {
        var str = template("ident-value-tmpl",{});
        document.getElementById("ident-value-tmpl-box").innerHTML = str;

        form.render('select')
    }

    /*获取数据分组表格数据*/
    function getIdentGroupTableData(){
        var req={
            current: current,
            size: pageSize,
            name:groupName
        };
        axios.get(macroUrl.group.queryList,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    renderGroupTable(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    /*渲染分组表格*/
    function renderGroupTable(data) {
        table.render({
            elem: '#identGroupTable',
            cellMinWidth: 100,
            page: false,
            size: 'sm', //小尺寸的表格
            data:data.records,
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'name', align: 'center', title: '名称'},
                {field: 'memo', align: 'center', title: '描述'},
                {align: 'center', toolbar: '#ident-group-tableHandle-box', title: '操作', minWidth: 120}
            ]]
        });

            laypage.render({
                elem: 'page-box'
                ,count: data.total,
                limit:pageSize,
                groups:1,
                curr:current
                ,layout: ['count','prev','page', 'next']
                ,jump: function(obj, first){
                    if(!first){
                        current = obj.curr;
                        getIdentGroupTableData();
                    }
                }
            });

        var divbox = $("#identGroupTable").next(".layui-table-view");
        $(divbox).find("table tr").eq(1).click();
    }

    /*显示新增分组弹窗*/
    function showAddGroupModel() {
        admin.open({
            type: 1,
            title: '新增分组',
            offset: "auto",
            content: $('#model-add-Group').html(),
            success: function (layero, dIndex) {
                form.render('checkbox');
                // 表单提交事件
                form.on('submit(addGroupSubmit)', function (data) {
                    layer.load(2);
                    var req = {
                        name:data.field.name,
                        memo:data.field.memo,
                        status:data.field.hasOwnProperty("status")?1:0
                    }
                    axios({
                        method: 'POST',
                        url:macroUrl.group.addGroup,
                        data:req,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg("新增成功", {icon: 1});
                                getIdentGroupTableData();
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, { icon: 2 });
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });

                    return false;
                });
            }
        });
    }

    /*显示编辑分组弹窗*/
    function showGroupEditModel(obj) {
        admin.open({
            type: 1,
            title: '编辑分组',
            offset: "auto",
            content: $('#model-edit-Group').html(),
            success: function (layero, dIndex) {
                if(obj.status){
                    obj.status = true;
                }
                // 回显数据
                form.val('editGroupForm', obj);
                // 表单提交事件
                form.on('submit(editGroup)', function (data) {
                    layer.load(2);
                    let req = {
                        id:obj.id,
                        version:obj.version,
                        memo:data.field.memo,
                        name:data.field.name,
                        status:data.field.hasOwnProperty('status')?1:0
                    }
                    axios({
                        method: 'put',
                        url:macroUrl.group.editGroup,
                        data:req,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (res) {
                            if (res.status == 200&&res.data.message=="success") {
                                layer.close(dIndex);
                                layer.closeAll('loading');
                                layer.msg("编辑成功", {icon: 1});
                                getIdentGroupTableData();
                                isClickRowTool = false;
                            } else {
                                layer.closeAll('loading');
                                layer.msg(res.data.message, {icon: 2});
                            }
                        })
                        .catch(function (err) {
                            console.log(err);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        })
                    return false;
                });
            },
            end :function(){
                isClickRowTool = false;
            }
        });
    }
    /*显示删除分组弹窗*/
    function showGroupDeleteModel(obj) {
        parent.layer.confirm('确认删除吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1
        }, function (index) {
            parent.layer.close(index);
            axios({
                method: 'delete',
                url:macroUrl.group.deleteGroup+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        getIdentGroupTableData();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                    isClickRowTool = false;
                })
                .catch(function (err) {
                    console.log(err);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })

        },function () {//取消
            isClickRowTool = false;
        });
    }
    /*显示版本管理弹窗*/
    function showVersionModel(obj) {
        var str = template("ident-group-versiontableHandle-tmp",{});
        document.getElementById("ident-group-version-tableHandle-box").innerHTML = str;

        admin.open({
            type: 1,
            title: '版本管理',
            offset: "auto",
            area: '745px',
            content: $('#mode-version-Group').html(),
            success: function (layero, dIndex) {
                gid = obj.id;
                getVersionList(function(versionList){
                    renderVersionList(versionList);
                });

                // 添加版本表单提交事件
                form.on('submit(addVersion)', function (data) {
                    let req  = {
                        identid:gid,
                        value:data.field.value,
                        memo:data.field.memo,
                    }
                    axios({
                        method: 'POST',
                        url:macroUrl.version.addVersion,
                        data:req,
                        headers:{
                            'Authorization':Authorization
                        }
                    })
                        .then(function (response) {
                            if(response.status == 200 &&response.data.message == "success"){
                                layer.closeAll('loading');
                                layer.msg("添加成功", {icon: 1});
                                getVersionList(function (versionList) {
                                    var obj = {
                                        versionList:versionList
                                    }
                                    var str = template("version-tmpl",obj);
                                    document.getElementById("version-tmpl-box").innerHTML = str;
                                    form.render('select');
                                    renderVersionList(versionList);
                                });
                            }else{
                                layer.closeAll('loading');
                                layer.msg(response.data.message, { icon: 2 });
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                            if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                                // 进行重新登陆
                                localStorage.clear();
                                top.location.href=loginPageUrl;
                            }
                        });

                    return false;
                });

                // 表格工具条点击事件
                table.on('tool(identGroupVersionTable)', function (obj) {
                    var data = obj.data;
                    var layEvent = obj.event;
                    if (layEvent === 'delete') { // 删除
                        deleteVersion(data);
                    }
                });
            },
            end: function () {//重新渲染版本下拉框，防止版本已经被更改过
                isClickRowTool = false;

                getVersionList(function (versionList) {
                    versionArr = versionList;
                    if(versionList.length>0){
                        var obj = {
                            versionList:versionList
                        }
                        var str = template("version-tmpl",obj);
                        document.getElementById("version-tmpl-box").innerHTML = str;
                        form.render('select');
                        vid = versionList[0].id;
                        getIdentRootValue();
                    }else{
                        $("#treeTbTree").empty();
                        $("#version-tmpl-box").empty();
                        form.render('select');
                    }
                });
            }
        });

    }
    /*打开新增分组值弹窗*/
    function openAddIdentValueModel(data) {
        window.addIdenValStatus=false;
        window.IdenValReq = {
            mid:gid,
            vid:vid,
            valueVersion:'',
            parId:IdentValueSelected.id,

        }
        for(let i in versionArr){
            if(versionArr[i].id == vid){
                window.IdenValReq.valueVersion = versionArr[i].value;
            }
        }
        admin.open({
            title: '新增分组值',
            url: 'ident/addIdentValue.html',
            end: function () {
                if (window.addIdenValStatus) {  // 判断表单操作成功标识，也可以使用top.xxx
                    getIdentRootValue();
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
    /*打开编辑分组值弹窗*/
    function openEditIdentValueModel(obj) {
        window.selectedIdenVal = obj;
        window.editIdenValStatus=false;
        admin.open({
            title: '编辑分组值',
            url: 'ident/editIdentValue.html',
            end: function () {
                if (window.editIdenValStatus) {  // 判断表单操作成功标识，也可以使用top.xxx
                    getIdentRootValue();
                }
            },
            success: function (layero, dIndex) {
                // 弹窗超出范围不出现滚动条
                $(layero).children('.layui-layer-content').css('overflow', 'visible');
            }
        });
    }
    /*打开删除分组值弹窗*/
    function openDeleteIdentValueModel(obj) {
        parent.layer.confirm('确认删除吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1
        }, function (index) {
            parent.layer.close(index);
            layer.load(2);
            axios({
                method: 'delete',
                url:macroUrl.idenval.deleteVal+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("成功删除", {icon: 1});
                        getIdentRootValue();
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }
    /*打开导入分组值弹窗*/
    function openImportIdentValueModel() {
        layui.use(['admin','table'], function () {
            var $ = layui.jquery;
            var admin = layui.admin;
            var form = layui.form;
            var table = layui.table;

            admin.open({
                title: '导入分组值',
                url: 'ident/importIdentValue.html',
                end: function () {

                },
                success: function (layero, dIndex) {
                    // 弹窗超出范围不出现滚动条
                    $(layero).children('.layui-layer-content').css('overflow', 'visible');
                }
            });
        })
    }

    /*获取版本列表*/
    function getVersionList(callback) {
        var req={
            identid: gid
        };
        var url = macroUrl.version.queryVersion+gid;
        axios.get(url,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    callback(data);
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }
    /*渲染版本列表*/
    function renderVersionList(versionList) {
        // 渲染表格
        table.render({
            elem: '#identGroupVersionTable',
            size: 'sm', //小尺寸的表格
            skin:'nob',
            data:versionList,
            page: false,
            cellMinWidth: 100,
            cols: [[
                {type:'numbers', title: '#'},
                {field: 'value', align: 'center', title: '值'},
                {field: 'memo', align: 'center', title: '备注'},
                {align: 'center', toolbar: '#ident-group-version-tableHandle-box', title: '操作', minWidth: 120}
            ]]
        });
    }

    /*获取分组值根目录*/
    function getIdentRootValue(){
        getIdentValue('root',function (resArr) {
            var dataarr = [{"data_type":0,
                "id":"root",
                "name":"根目录",
                "par_id":"",
                "version":"0",
                "isParent":true,
                "sub":resArr
            }];
            var treeObj = $.fn.zTree.init($("#treeTbTree"), setting.identValueSetting, dataarr);
            var nodes = treeObj.getNodes();
            if (nodes.length>0) {
                treeObj.expandNode(nodes[0], true, false, true);
            }
        });
    }
    /*获取分组值*/
    function getIdentValue(parent_code ,callback) {
        var req={
            mid : gid,
            parId :parent_code ,
            vid:vid
        };
        var url = macroUrl.idenval.queryIdenval;
        axios.get(url,{
            params: req,
            headers:{
                'Authorization':Authorization
            }
        })
            .then(function (response) {
                if(response.status == 200 &&response.data.message == "success"){
                    var data = response.data.data;
                    var resArr = [];
                    zhuanHuanTree(data,resArr);
                    callback(resArr)
                }
            })
            .catch(function (error) {
                console.log(error);
                if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                    // 进行重新登陆
                    localStorage.clear();
                    top.location.href=loginPageUrl;
                }
            });
    }

    //查询下方区划树的下级区划值（懒加载）
    function onExpandIdentValueTree(event, treeId, treeNode) {
        console.log(treeNode)
        if(treeNode.sub.length>0){
            return false;
        }else{
            getIdentValue(treeNode.id,function (resArr) {
                const treeObj = $.fn.zTree.getZTreeObj("treeTbTree");
                treeObj.addNodes(treeNode, resArr);
            });
        }

    }

    //转换菜单集合数据
    function zhuanHuanTree(tdata,resData) {
        if(Array.isArray(tdata) && tdata.length>0){
            tdata.forEach(function(v,i){
                var newValue=v.name;
                resData[i]=v;
                resData[i].title=newValue;
                resData[i].icon = "";
                resData[i].isParent = "true";
                resData[i].sub = [];
            });
        }
    }

    //选中分组值
    function identValueOnClick(event, treeId, treeNode){
        IdentValueSelected = treeNode;
    }

    /*删除版本*/
    function deleteVersion(obj){
        layer.confirm('确认删除吗？', {
            skin: 'layui-layer-admin',
            size:'sm',
            shade: .1,
        }, function (i,dIndex) {//确定
            layer.close(i);
            layer.load(2);
            axios({
                method: 'delete',
                url:macroUrl.version.deleteVersion+obj.id,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (res) {
                    if (res.status == 200&&res.data.message=="success") {
                        layer.closeAll('loading');
                        layer.msg("删除成功", {icon: 1});
                        getVersionList(function(versionList){
                            var obj = {
                                versionList:versionList
                            }
                            var str = template("version-tmpl",obj);
                            document.getElementById("version-tmpl-box").innerHTML = str;
                            form.render('select');
                            renderVersionList(versionList);
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.data.message, {icon: 2});
                    }
                })
                .catch(function (err) {
                    console.log(err);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                })
        });
    }

});

